package pkg.register;

import javax.servlet.http.*;

import org.apache.struts.action.*;

import retail.bo.CustomerBo;
import HibernateBeans.CustomerDetails;
import HibernateBeans.RepDetails;
import HibernateBeans.Users;

public class RegisteringAction extends Action {
	private CustomerBo customerBo;
	
	public CustomerBo getCustomerBo() {
		return customerBo;
	}

	public void setCustomerBo(CustomerBo customerBo) {
		this.customerBo = customerBo;
	}

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		HttpSession session = request.getSession();

		DynaActionForm myForm = (DynaActionForm) form;

		String role = (String) session.getAttribute("role");
		Users user = new Users(myForm.getString("username"),
				myForm.getString("password"));
		String cpass=myForm.getString("cpassword");
		String first = myForm.getString("first_name");
		String last = myForm.getString("last_name");
		String roles;
		if(role.equals("Customer"))
			roles="user";
		else
			roles="admin";
		if(!user.getUser_pass().equals(cpass)){
			session.setAttribute("error", "Error: Password does not match Confirm Password");
			return mapping.findForward("error");
		}
		if (role.equals("Customer")) {
			String passcode = myForm.getString("passcode");
			String answer = myForm.getString("security_answer");
			CustomerDetails cd = (CustomerDetails) session.getAttribute("user");
			if (!(cd.getFirst_name().equals(first)
					&& cd.getLast_name().equals(last))){
				session.setAttribute("error", "Error: User info does not match");
				return mapping.findForward("error");}
			if(!(cd.getSecurity_answer().compareToIgnoreCase(answer)==0)){
				session.setAttribute("error", "Security Answer is wrong");
				return mapping.findForward("error");
			}
			if(!(cd.getPasscode().compareToIgnoreCase(passcode)==0)){
				session.setAttribute("error", "Passcode incorrect");
				return mapping.findForward("error");
			}
			cd.setUser(user);
			customerBo.addUser(user,roles);
			customerBo.updateCustomer(cd);
		}
		if (role.equals("Representative")) {
			RepDetails rd=(RepDetails) session.getAttribute("user");
			if(!(rd.getFirst_name().equals(first)&&rd.getLast_name().equals(last))){
				session.setAttribute("error", "User info is wrong");
				return mapping.findForward("error");
			}
			rd.setUser(user);
			customerBo.addUser(user,roles);
			customerBo.updateRep(rd);
		}	
			return mapping.findForward("success");
	}
}